package com.flca.frw.zk.comp;

import java.lang.reflect.Method;

import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Constraint;
import org.zkoss.zul.Datebox;
import org.zkoss.zul.Decimalbox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Longbox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import org.zkoss.zul.impl.InputElement;

import com.flca.frw.util.TransformUtils;
import com.flca.frw.zk.util.Alert;
import com.flca.frw.zk.util.WindowHelper;

public class FormItemCtrl extends Window implements IFormItem {

	private static final long serialVersionUID = -9189363508006446234L;

	private static TransformUtils tu = TransformUtils.getInstance();
	
	private WindowHelper wh = new WindowHelper(this);
	
	public void updateView(Object value) 
	{
		try {
			Component comp = getComp();
			
			if (comp instanceof Textbox) {
				((Textbox) comp).setValue(tu.object2String(value));
			} else if (comp instanceof Decimalbox) {
				((Decimalbox) comp).setValue(tu.object2BigDecimal(value));
			} else if (comp instanceof Intbox) {
				((Intbox) comp).setValue(tu.object2Integer(value));
			} else if (comp instanceof Longbox) {
				((Longbox) comp).setValue(tu.object2Long(value));
			} else if (comp instanceof Datebox) {
				((Datebox) comp).setValue(tu.object2Date(value));
			}
		} catch (Exception e) {
			Alert.show("FormItemCtrl.updateView() : " + e);
		}	
	}
	
	public void updateModel(Object aTargetObject, Method setter) 
	{
		try {
			InputElement comp = getComp();
			Object value = (comp).getRawValue();
			if (value != null) {
				wh.setValue(value, setter, aTargetObject);
			} else {
				setter.invoke(aTargetObject, new Object[] {null});
			}
		} catch (Exception e) {
			Alert.show("fout tijdens FormItemCtrl.updateModel " + e );
		} 
		
	}

	public void validate(Constraint constraint) {
		wh.validate("idInput", constraint);
	}

	public void validateNotEmpty() 
	{
		wh.validateNotEmpty("idInput");
	}
	

	private InputElement getComp() 
	{
		InputElement result = (InputElement) getFellow("idInput");
		return result;
	}
	
	
}
